package com.itheima.userdemo.controller;

import com.itheima.userdemo.pojo.User;
import com.itheima.userdemo.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    // doGet doPost?

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost...");
        // 1. 接收用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username+" "+password);
        // 2. 调用Service查询用户
        UserService userService = new UserService();
        User dbUser = userService.findUserByUsernamePassword(username,password);
        // 3. 判断用户
        if(dbUser == null){
            // 在登录页面上，显示后台返回的错误信息
            req.setAttribute("errMessage","用户名或密码错误，请重新输入");
            // 请求转发回登录页面，目的就是在页面上使用EL表达式，显示错误信息
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else{
            // 登录成功

            // 登录成功，往Session存当前的用户名
            req.getSession().setAttribute("username",username);


            // 思路：先判断是否勾选了记住用户名，然后再使用Cookie
            String rememberValue = req.getParameter("remember");
            // 如果没有选择，rememberValue是null rememberValue.equals("1")空指针异常
            System.out.println(rememberValue);
            if("1".equals(rememberValue)){
                // 选择了记住用户名和密码，使用cookie
                Cookie userCookie = new Cookie("username", username);
                Cookie passCookie = new Cookie("password", password);
                // 设置Cookie的保持时间
                userCookie.setMaxAge(60*60*24*7);
                passCookie.setMaxAge(60*60*24*7);
                resp.addCookie(userCookie);
                resp.addCookie(passCookie);
            }
            req.setAttribute("username",username);
            // 请求转发主页
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }
    }
}
